package com.xiaobai.netease_news.client;

import android.util.Log;

import com.xiaobai.netease_news.model.Video;
import com.xiaobai.netease_news.utils.CommonHttpUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by PiscesQ on 2015/6/25.
 */
public class ClientAPI {

    //视频get请求：http://c.m.163.com/nc/video/list/V9LG4B3A0/n/0-10.html
    public static JSONObject getData(String path) {
        JSONObject ret = null;
        byte[] bytes = CommonHttpUtil.doGet(path, null);
        try {
            String data = new String(bytes, 0, bytes.length, "UTF-8");
            ret = new JSONObject(data);
        } catch (UnsupportedEncodingException e) {
            Log.e("ClientAPI", "未知编码异常");
            e.printStackTrace();
        } catch (JSONException e) {
            Log.e("ClientAPI", "JSON异常");
            e.printStackTrace();
        } catch (NullPointerException e) {
            Log.e("ClientAPI", "数据加载异常--NullPointerException");
            e.printStackTrace();
        }
        return ret;
    }

    //数据解析方法
    public static List<Video> handleVideoJSON(JSONObject jsonObject) {
        List<Video> ret = null;
        try {
            JSONArray array = jsonObject.getJSONArray("V9LG4B3A0");
            ret = new ArrayList<>();
            for (int i = 0; i < array.length(); i++) {
                JSONObject video = (JSONObject) array.get(i);
                Video v = new Video();
                v.parseJson(video);
                ret.add(v);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return ret;
    }
}
